#include "Comment.hpp"
#include <thread>  // 用于多线程处理

#define listen_sum 8
#define SIZE 1024

// 处理客户端连接的函数
void handle_client(int client_sockfd) {
    char buffer[SIZE] = {0};
    int n;
    
    // 持续读取客户端发送的数据
    while ((n = read(client_sockfd, buffer, sizeof(buffer)-1)) > 0) {
        buffer[n] = '\0';
        cout << "收到客户端消息: " << buffer << endl;
        
        // 可以在这里添加回复客户端的逻辑
        // write(client_sockfd, "收到消息", 8);
        
        // 清空缓冲区
        bzero(buffer, SIZE);
    }
    
    if (n < 0) {
        cout << "读取客户端数据错误" << endl;
    } else {
        cout << "客户端断开连接" << endl;
    }
    
    // 关闭客户端套接字
    close(client_sockfd);
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        cout << "使用方法: " << argv[0] << " 端口号" << endl;
        return 1;  // 参数错误时退出程序
    }
    
    cout << "服务器启动成功，监听端口: " << argv[1] << endl;
    
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        cout << "创建套接字错误" << endl;
        return 1;
    }
    
    // 设置套接字选项，允许端口重用
    int opt = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    
    // 进行数据填充
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(stoi(argv[1]));
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    // 进行bind
    int n = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (n < 0) {
        cout << "绑定套接字错误" << endl;
        close(sockfd);
        return 1;
    }
    
    // 进行监听
    int m = listen(sockfd, listen_sum);
    if (m < 0) {
        cout << "监听套接字错误" << endl;
        close(sockfd);
        return 1;
    }
    
    // 接受客户端连接
    while (true) {
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
        
        if (client_sockfd < 0) {
            cout << "接受客户端连接错误" << endl;
            continue;
        }
        
        cout << "新客户端连接" << endl;
        
        // 创建新线程处理客户端通信
        thread client_thread(handle_client, client_sockfd);
        // 分离线程，使其独立运行
        client_thread.detach();
    }
    
    // 关闭服务器套接字（实际上这里永远不会执行到）
    close(sockfd);
    return 0;
}